package com.lkd.shoppingcart.dao.impl;

import java.util.List;

import com.lkd.shoppingcart.dao.CartDao;
import com.lkd.shoppingcart.entity.CartItemView;

public class CartDaoImpl extends BaseDao implements CartDao {

	@Override
	public int addToCart(Integer userId, Integer productId, Integer quantity) {
		String sql = "insert into cart_item(userId, productId, quantity) values(?, ?, ?)";
		return update(sql, userId, productId, quantity);
	}

	@Override
	public int removeById(Integer userId, Integer productId) {
		String sql = "delete from cart_item where userId = ? and productId = ?";
		return update(sql, userId, productId);
	}

	@Override
	public int removeByUserId(Integer userId) {
		String sql = "delete from cart_item where userId = ?";
		return update(sql, userId);
	}

	@Override
	public int updateQuantityById(Integer userId, Integer productId, Integer quantity) {
		String sql = "update cart_item set quantity = ? where userId = ? and productId = ?";
		return update(sql, quantity, userId, productId);
	}
	
	@Override
	public int queryForCount(Integer userId) {
		String sql = "select count(*) from cart_item where userId = ?";
		Number count = (Number) queryForSingleValue(sql, userId);
		return count.intValue();
	}

	@Override
	public List<CartItemView> queryByUserId(Integer userId) {
		String sql = "select userId, productId, productName, price, quantity from cart_item_view where userId = ?";
		return queryForList(CartItemView.class, sql, userId);
	}

	@Override
	public boolean cartExists(Integer userId, Integer productId) {
		String sql = "select exists(select * from cart_item where userId = ? and productId = ?)";
		Number result = (Number) queryForSingleValue(sql, userId, productId);
		if (result.intValue() == 1) {
			return true;
		}
		return false;
	}

}
